package com.draven.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * MinIO配置类
 */
@Slf4j
@Data
@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 初始化MinioClient
     */
    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    /**
     * 初始化Bucket
     */
    @PostConstruct
    public void init() {
        try {
            // 直接创建一个新的MinioClient实例，而不是使用Bean
            MinioClient minioClientLocal = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
                    
            boolean isExist = minioClientLocal.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                minioClientLocal.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("创建存储桶 {} 成功", bucketName);
            }
        } catch (Exception e) {
            log.error("初始化MinIO失败: {}", e.getMessage(), e);
        }
    }
} 